package com.jinzhi.jzweb.controller;


import java.util.*;

import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.domain.IntegralSpecificationInventoryDO;
import com.jinzhi.jzweb.service.IntegralSpecificationInventoryService;
import com.jinzhi.jzweb.utils.IDUtil;
import lombok.val;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.domain.IntegralStoreCommodityDO;
import com.jinzhi.jzweb.service.IntegralStoreCommodityService;
import com.jinzhi.common.utils.Result;

/**
 * 
 * <pre>
 * 积分商城货品表
 * </pre>
 * <small> 2023-02-16 09:04:42 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/integralStoreCommodity")
public class IntegralStoreCommodityController extends BaseController {
	@Autowired
	private IntegralStoreCommodityService integralStoreCommodityService;

	@Autowired
	private IntegralSpecificationInventoryService integralSpecificationInventoryService;
	
	@GetMapping()
	@RequiresPermissions("jzweb:integralStoreCommodity:integralStoreCommodity")
	String IntegralStoreCommodity(){
	    return "jzweb/integralStoreCommodity/integralStoreCommodity";
	}




	@GetMapping("/updateInventory/{id}")
	@RequiresPermissions("jzweb:integralStoreCommodity:updateInventory")
	String updateInventory(@PathVariable("id") Long id,Model model){
		IntegralStoreCommodityDO integralStoreCommodityDO = integralStoreCommodityService.selectById(id);
		List<String> list = splitStrArrayList(integralStoreCommodityDO.getSpecificationId());
		List<IntegralSpecificationInventoryDO> rstList = integralSpecificationInventoryService.selectBatchIds(list);
		model.addAttribute("rstList",rstList);
		return "jzweb/integralStoreCommodity/updateInventory";
	}



	/**
	 *
	 * @param ids   id
	 * @param specificationQuantitys  库存数量
	 * @param specifications 商品规格
	 * @return
	 */
	@PostMapping("/editInventory")
	@RequiresPermissions("jzweb:integralStoreCommodity:editInventory")
	ApiResult editInventory(String[] ids, String[] specificationQuantitys, String[] specifications){
		List<IntegralSpecificationInventoryDO> integralSpecificationInventoryDOS =new ArrayList<>();

		for (int i=0;i<ids.length;i++){
			IntegralSpecificationInventoryDO integralSpecificationInventoryDO =new IntegralSpecificationInventoryDO();
			integralSpecificationInventoryDO.setId(ids[i]);
			integralSpecificationInventoryDO.setSpecificationQuantity(Integer.valueOf(specificationQuantitys[i]));
			integralSpecificationInventoryDO.setSpecification(specifications[i]);
			integralSpecificationInventoryDOS.add(integralSpecificationInventoryDO);
		}
		return ApiResult.success(integralSpecificationInventoryService.updateBatchById(integralSpecificationInventoryDOS));
	}




	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:integralStoreCommodity:integralStoreCommodity")
	public Result<Page<IntegralStoreCommodityDO>> list(IntegralStoreCommodityDO integralStoreCommodityDTO){
		// 查询列表数据
		Page<IntegralStoreCommodityDO> page = integralStoreCommodityService.selectPage(getPage(IntegralStoreCommodityDO.class),
					integralStoreCommodityService.convertToEntityWrapper().orderBy("id", false));
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
				IntegralStoreCommodityDO obj = (IntegralStoreCommodityDO) page.getRecords().get(i);
			List<String> intList = splitStrArrayList(obj.getSpecificationId());
			obj.setIntegralSpecificationInventories((List<IntegralSpecificationInventoryDO>) integralSpecificationInventoryService.selectBatchIds(intList));
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}


	private static List<String> splitStrArrayList(String str) {
		List<String> stringList = new ArrayList<>();
		if (str != null) {
			String[] strs = str.split(",");
			stringList.addAll(Arrays.asList(strs));
			return stringList;
		}
		return null;
	}
	@GetMapping("/add")
	@RequiresPermissions("jzweb:integralStoreCommodity:add")
	String add(){
	    return "jzweb/integralStoreCommodity/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:integralStoreCommodity:edit")
	String edit(@PathVariable("id") Long id,Model model){
		IntegralStoreCommodityDO integralStoreCommodity = integralStoreCommodityService.selectById(id);
		List<String> intList = splitStrArrayList(integralStoreCommodity.getSpecificationId());

		List<IntegralSpecificationInventoryDO> list = integralSpecificationInventoryService.selectBatchIds(intList);
		List<Map> rst =new ArrayList<>();
		for (int i=0;i<list.size();i++){
			Map map =new HashMap();
			map.put("id",list.get(i).getId());
			map.put("name",list.get(i).getSpecification());
			map.put("quantity",list.get(i).getSpecificationQuantity());
			rst.add(map);
		}

		integralStoreCommodity.setSpecificationName(rst.toString());
		model.addAttribute("integralStoreCommodity", integralStoreCommodity);
	    return "jzweb/integralStoreCommodity/edit";
	}
	
	@Log("添加积分商城货品表")
	@ResponseBody
	@PostMapping("/save")
	@Transactional
	@RequiresPermissions("jzweb:integralStoreCommodity:add")
	public Result<String> save( IntegralStoreCommodityDO integralStoreCommodity){
		String specificationId = "";
		integralStoreCommodity.setState(1);
		integralStoreCommodity.setCreateTime(new Date());

		String[] array = splitStrArray(integralStoreCommodity.getSpecificationName());
		List<IntegralSpecificationInventoryDO> list =new ArrayList<>();
		IntegralSpecificationInventoryDO integralSpecificationInventoryDO = new IntegralSpecificationInventoryDO();;
		for (int i=0;i<array.length;i++){
			if (i%2==0){ //偶数
				integralSpecificationInventoryDO.setSpecification(array[i]);
			}else{
				integralSpecificationInventoryDO.setSpecificationQuantity(Integer.valueOf(array[i]));
			}
			if (i%2!=0) {
				list.add(integralSpecificationInventoryDO);
			}
			if (i%2!=0) {
				integralSpecificationInventoryDO = new IntegralSpecificationInventoryDO();
			}
		}
		for (int i=0;i<list.size();i++){
			String id = getId(); //生成id
			if (StringUtil.isNull(specificationId)){
				specificationId = id;
			}else {
				specificationId = specificationId+","+id;
			}
			list.get(i).setId(id);
		}

		integralStoreCommodity.setSpecificationId(specificationId);
		integralSpecificationInventoryService.insertBatch(list);


		integralStoreCommodityService.insert(integralStoreCommodity);

        return Result.ok();
	}


	//生成一个随机id
	private String getId(){
		IDUtil idUtil = new IDUtil("yyyyMMddmmssSSS");//yyyy-MM-dd HH:mm:ss：SSS
		return idUtil.generatedNoByFormatDateAndRandom(3,"3");
	}


	public static String[] splitStrArray(String str) {
		if (str != null) {
			return str.split(",");
		}
		return null;
	}
	
	@Log("修改积分商城货品表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:integralStoreCommodity:edit")
	public Result<String>  update( IntegralStoreCommodityDO integralStoreCommodity){
		IntegralStoreCommodityDO integralStoreCommodityDO = integralStoreCommodityService.selectById(integralStoreCommodity.getId());
		integralStoreCommodityDO.setType(integralStoreCommodity.getType());
		integralStoreCommodityDO.setCommodityName(integralStoreCommodity.getCommodityName());
		integralStoreCommodityDO.setCommodityPrices(integralStoreCommodity.getCommodityPrices());
		integralStoreCommodityDO.setIntegralQuantity(integralStoreCommodity.getIntegralQuantity());
		integralStoreCommodityDO.setCommodityDescribe(integralStoreCommodity.getCommodityDescribe());
		integralStoreCommodityDO.setSpecificationId(integralStoreCommodity.getSpecificationId());
		integralStoreCommodityDO.setInventoryQuantity(integralStoreCommodity.getInventoryQuantity());
		integralStoreCommodityDO.setParameter(integralStoreCommodity.getParameter());
		integralStoreCommodityDO.setCommodityImg(integralStoreCommodity.getCommodityImg());
		integralStoreCommodityDO.setThreshold(integralStoreCommodity.getThreshold());
		integralStoreCommodityDO.setCreateTime(integralStoreCommodity.getCreateTime());
		integralStoreCommodityDO.setUpdateTime(integralStoreCommodity.getUpdateTime());
		integralStoreCommodityDO.setCommodityParticularsImg(integralStoreCommodity.getCommodityParticularsImg());
		integralStoreCommodityDO.setSort(integralStoreCommodity.getSort());
		integralStoreCommodityDO.setState(integralStoreCommodity.getState());
		integralStoreCommodityDO.setSpecificationName(integralStoreCommodity.getSpecificationName());
		boolean update = integralStoreCommodityService.updateById(integralStoreCommodity);
		return update ? Result.ok() : Result.fail();
	}


	@Log("查询用户积分详情接口")
	@ResponseBody
	@RequestMapping("/selectIntegralById")
	public Result<Object>  selectIntegralById(String id){
		return Result.ok(integralStoreCommodityService.selectById(id));
	}


	@Log("删除积分商城货品表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:integralStoreCommodity:remove")
	@Transactional
	public Result<String>  remove( Long id){
		String specificationId = integralStoreCommodityService.selectById(id).getSpecificationId();
		String[] array = splitStrArray(specificationId);
		for (int i=0;i<array.length;i++){
			integralSpecificationInventoryService.deleteById(array[i]);
		}
		integralStoreCommodityService.deleteById(id);

        return Result.ok();
	}
	
	@Log("批量删除积分商城货品表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:integralStoreCommodity:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		integralStoreCommodityService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}
	
}
